<template>
  <div class="search">
    <div class="header">
      <span
        class="iconfont iconjiantou2"
        @click="$router.back()"
      ></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
      />
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <p
        v-for="(v,i) in historyList"
        :key="i"
        @click="onSearch(v,$event)"
      >{{v}}</p>
    </div>
    <div class="searchList">
      <h2>搜索结果</h2>
      <router-link
        :to="{path:`/articleDetail/${v.id}`}"
        v-for="(v,i) in searchList"
        :key='i'
      >{{v.title}}</router-link>
    </div>
  </div>
</template>

<script>
import { post_search } from "@/apis/article.js";
export default {
  data() {
    return {
      userKey: "",
      searchList: [],
      historyList: [],
    };
  },
  methods: {
    async onSearch(v, e) {
      console.log(v);
      if (v) {
        this.userKey = v;
      }
      this.searchList = (await post_search(this.userKey)).data.data;
      this.historyList.splice(this.historyList.indexOf(this.userKey), 1);
      this.historyList.unshift(this.userKey);
      localStorage.setItem("hm_search", JSON.stringify(this.historyList));
    },
  },
  mounted() {
    this.historyList = JSON.parse(localStorage.getItem("hm_search")) || [];
  },
};
</script>

<style lang='less' scoped>
.header {
  display: flex;
  height: 50px;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  border-bottom: 1px solid #ccc;
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.historyList,
.searchList {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  h2 {
    line-height: 40px;
    font-weight: bold;
  }
  > a {
    display: block;
    text-decoration: underline;
    line-height: 30px;
    color: #666;
    // 添加样式让文本一行显示，超出的部分使用...替换
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  p {
    line-height: 30px;
    border-bottom: 1px dashed orange;
  }
}
</style>